<?php

namespace app\traits;

use GuzzleHttp\Client;
use think\facade\Cache;
use think\facade\Log;

trait TemplateMsgTrait
{
    /**
     * @param $openid 用户openid
     * @param $templateId 模板Id
     * @param $pagePath  小程序跳转地址
     * @param array $data 模板数据
     * @return mixed
     */
    public function uniformMessageSend($openid, $templateId, $data = [], $pagePath = 'pages/home/index')
    {
        if (!$openid || !$templateId || !$data) {
            return ['code' => -1, 'msg' => '缺少参数', 'data' => []];
        }
        if (!is_array($data)) {
            return ['code' => -1, 'msg' => '模板数据格式错误', 'data' => []];
        }
        $accessToken = Cache::get('access_token');
        $client = new Client();
        if (!$accessToken) {
            $accessTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . config('app.mp.appid') . '&secret=' . config('app.mp.secret');
            try {
                $response = $client->get($accessTokenUrl, ['timeout' => 5]);
            } catch (\Exception $e) {
                return ['code' => -1, 'msg' => $e->getMessage(), 'data' => []];
            }
            $result = json_decode($response->getBody()->getContents(), true);
            if (isset($result['errcode'])) {
                Log::info($result);
                return ['code' => -1, 'msg' => $result['errmsg'], 'data' => $result];
            }
            Cache::set('access_token', $result['access_token'], 7000);
            $accessToken = $result['access_token'];
        }
        $subscribeMsgUrl = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=' . $accessToken;
        $payload = [
            'touser' => $openid,
            'mp_template_msg' => [
                'appid' => config('app.mp_wx.appid'),
                'template_id' => $templateId,
                'miniprogram' => [
                    'appid' => config('app.mp.appid'),
                    'pagepath' => $pagePath
                ],
                'data' => $data
            ]
        ];
        try {
            $uniformResponse = $client->post($subscribeMsgUrl, ['body' => json_encode($payload), 'headers' => ['Content-Type' => 'application/json'], 'timeout' => 5]);
        } catch (\Exception $e) {
            return ['code' => -11, 'msg' => $e->getMessage(), 'data' => []];
        }
        $uniformResult = json_decode($uniformResponse->getBody()->getContents(), true);
        if (isset($uniformResult['errcode']) && $uniformResult['errcode'] != 0) {
            $errorMsg = $this->getErrorMsg($uniformResult['errcode']);
            Log::info($uniformResult);
            return ['code' => -1, 'msg' => $errorMsg, 'data' => $uniformResult];
        }
        return ['code' => 1, 'msg' => 'success', 'data' => $uniformResult];
    }

    public function getErrorMsg($errCode)
    {
        $errMsg = '发送失败';
        switch ($errCode) {
            case 40037:
                $errMsg = '模板id不正确';
                break;
            case 41028:
                $errMsg = 'form_id过期或者不正确';
                break;
            case 41029:
                $errMsg = 'form_id已被使用';
                break;
            case 41030:
                $errMsg = '小程序页面路径不正确';
                break;
            case 45009:
                $errMsg = '接口调用超过限额';
                break;
            case 40003:
                $errMsg = '不是正确的openid';
                break;
            case 40013:
                $errMsg = 'appid不正确，或者不符合绑定关系要求';
                break;
            case 43004:
                $errMsg = '推送用户未关注抖物库公众号';
                break;
        }
        return $errMsg;
    }
}